package com.itheima.leyou.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.leyou.common.exception.LyException;
import com.itheima.leyou.mapper.SpecGroupMapper;
import com.itheima.leyou.po.SpecGroup;
import com.itheima.leyou.service.SpecGroupService;
import com.itheima.leyou.service.SpecParamService;
import com.leyou.item.dto.SpecGroupDTO;
import com.leyou.item.dto.SpecParamDTO;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class SpecGroupServiceImpl extends ServiceImpl<SpecGroupMapper , SpecGroup> implements SpecGroupService {

    @Autowired
    private SpecParamService specParamService;
    @Override
    public List<SpecGroupDTO> querySpecGroupByCategory(Integer id) {

        return SpecGroupDTO.convertEntityList(this.query()
                .eq("category_id",id).list());
    }

    @Override
    @Transactional
    public void addGroup(SpecGroupDTO groupDTO) {
        save(groupDTO.toEntity(SpecGroup.class));

    }

    @Override
    @Transactional
    public void updateGroup(SpecGroupDTO groupDTO) {
        if(StringUtils.isNotBlank(String.valueOf(groupDTO.getId()))) {
            //有主键，进行修改操作
            this.updateById(groupDTO.toEntity(SpecGroup.class));
        }
    }

    @Override
    public List<SpecGroupDTO> listSpecGroup(Long categoryId) {
        //根分类id查询规格参数组信息,一个分类id对应多个规格参数组信息
        List<SpecGroupDTO> groupList = SpecGroupDTO
                .convertEntityList(query()
                        .eq("category_id", categoryId)
                        .list());
        if(CollectionUtils.isEmpty(groupList)){
            throw new LyException(404, "该分类下的规格组不存在！");
        }
        // 查询规格参数
        List<SpecParamDTO> paramList =specParamService.querySpecParam(categoryId, null, null);
        // 对规格参数分组，groupId一致的在一组
        Map<Long, List<SpecParamDTO>> map = paramList.stream().collect(Collectors.groupingBy(SpecParamDTO::getGroupId));
        // 把参数放入group
        for (SpecGroupDTO groupDTO : groupList) {
            groupDTO.setParams(map.get(groupDTO.getId()));
        }
        return groupList;

    }

}
